#define _CRT_SECURE_NO_WARNINGS
class Solution {
public:
    typedef pair<string, int> SI;
    struct CompareKV
    {
        bool operator()(const SI& x, const SI& y)
        {
            return (x.second > y.second) || (x.second == y.second && x.first < y.first);
        }
    };

    vector<string> topKFrequent(vector<string>& words, int k) {
        map<string, int> countMap;
        for (auto& ch : words)
        {
            countMap[ch]++;
        }
        vector<SI> sortV(countMap.begin(), countMap.end());
        sort(sortV.begin(), sortV.end(), CompareKV());

        vector<string> ret;
        for (size_t i = 0; i < k; i++)
        {
            ret.push_back(sortV[i].first);
        }

        return ret;
    }
};